package com.webServer.http;

import com.webServer.exception.EmptyRequestException;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.webServer.utils.ParseString.parseParameter;
import static com.webServer.utils.ParseString.readLine;

/**
 * @Auther:SYZ
 * @Date:2022/8/2 - 08 - 02 - 11:11
 * @Description:
 *      HTTP解析请求
 *      请求有三个部分:请求行,消息头,消息正文
 * @version:1.0
 */
public class HttpServletRequest {
    private Socket socket;  //接受客户端
    private String method;  //请求方式
    private String uri;     //抽象路径
    private String protocol;//协议版本
    //保存uri中"?"左侧的内容,如果没有则内容与uri一致
    private String requestURI;
    //保存uri中"?"右侧的内容,参数部分
    private String queryString;
    //保存参数部分的每一组参数
    private Map<String,String> parameters = new HashMap();
    //消息头相关信息
    private Map<String,String> headers = new HashMap<String, String>();

    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseHeaders();
        //1.3解析消息正文
        parseContent();
    }

    /***
     * 解析请求行
     * @throws IOException
     */
    private void parseRequestLine() throws IOException {
        //获取IO流的请求体
        String line = readLine(socket.getInputStream());
        if(line.isEmpty()){
            //不存在则抛出自定义异常
            throw new EmptyRequestException();
        }
        //将请求体按空格进行拆分
        String[] data = line.split("\\s");

        method = data[0];
        uri = data[1];
        protocol = data[2];
        //进一步解析uri
        parseURI();

        System.out.println("method: "+method);
        System.out.println("uri: "+uri);
        System.out.println("protocol: "+protocol);
    }
    private void parseURI() {
        //拆分uri
        String[] data = uri.split("\\?");
        requestURI = data[0];
        //判断'?'右侧是否有内容
        if(data.length>1){
            queryString = data[1];
            //解析uri参数
            parameters = parseParameter(queryString);
        }
        System.out.println("requestURI:" + requestURI);
        System.out.println("queryString:" + queryString);
        System.out.println("parameters:" + parameters);
    }

    /***
     * 解析信息头
     * @throws IOException
     */
    private void parseHeaders() throws IOException {
        while (true){
            String line = readLine(socket.getInputStream());
            if(line.isEmpty()){
                break;
            }
            System.out.println("消息头为: " +line);
            String[] data = line.split(":\\s");
            headers.put(data[0].toLowerCase(),data[1]);
        }
    }

    private void parseContent() throws IOException {
        //解析请求方式
        if("post".equalsIgnoreCase(method)){
            //消息头中是否包含Content-Length
            if(headers.containsKey("content-length")){
                int contentLength =
                        Integer.parseInt(headers.get("Content-length"));
                //创建正文一样大小的byte数组
                byte[] data = new byte[contentLength];
                InputStream in = socket.getInputStream();
                //将正文内容块读进data数组中备用
                in.read(data);

                //解析正文内容类型
                if(headers.containsKey("content-type")){
                    String contentType = headers.get("content-type");
                    //如果正文类型为form表单提交数据
                    if("application/x-www-form-urlencoded".equals(contentType)){
                        String line = new String(data, StandardCharsets.ISO_8859_1);
                        System.out.println("正文内容===========:"+line);
                        parameters = parseParameter(line);
                    }
                    //可后期扩展为 else if("xxx/xxx".equals(contentType))
                }
            }
        }
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    //根据参数名获取对应的参数值
    public String  getParameters(String name) {
        return parameters.get(name);
    }

    //根据消息头的名字获取对应消息头的值
    public String getHeaders(String name) {
        return headers.get(name.toLowerCase());
    }
}
